package com.guonl.help;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SqlPlaceholderParser3 {

    // 方法：匹配IN子句中的占位符，并返回它们的索引
    public static List<Integer> getPlaceholderIndices(String sql, String fieldName) {
        // 构建针对IN子句的正则表达式
        String regex = "\\b" + fieldName + "\\s+IN\\s*\\(\\s*\\?\\s*(,\\s*\\?\\s*)*\\)";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(sql);

        List<Integer> indices = new ArrayList<>();


        // 当匹配字段时，找到该字段的IN子句中的占位符位置
        if (matcher.find()) {
            String matchedClause = matcher.group();
            System.out.println(matchedClause);
            int fromIndex = sql.indexOf(matchedClause);
            int endIndex = fromIndex + matchedClause.length();
//            System.out.println("fromIndex：" + fromIndex);
//            System.out.println("endIndex：" + endIndex);

            int currentQuestionMarkIndex = -1; // 当前全局的问号索引
            // 统计全局问号的序列
            List<Integer> allQuestionMarkIndices = new ArrayList<>();
            for (int i = 0; i < sql.length(); i++) {
                if (sql.charAt(i) == '?') {
                    allQuestionMarkIndices.add(currentQuestionMarkIndex++);
                    if(i > fromIndex && i < endIndex){
                        indices.add(currentQuestionMarkIndex);
                    }
                }
            }

        }
        return indices;
    }


    public static void main(String[] args) {
        String sql = "SELECT user_id, user_name, phone FROM t_user WHERE user_name = ? and user_name = ? AND phone IN (?, ?, ?) and age IN (?,?,?)";

        // 测试phone字段的IN子句
        List<Integer> indices = getPlaceholderIndices(sql, "phone");
        System.out.println("phone IN clause indices: " + indices);

        List<Integer> ageIndices = getPlaceholderIndices(sql, "age");
        System.out.println("age IN clause indices: " + ageIndices);

//        // 测试user_name字段
//        indices = getPlaceholderIndices(sql, "user_name");
//        System.out.println("user_name indices: " + indices);
    }
}


